package parser;

import java.io.PrintWriter;
import java.util.ArrayList;
import lexer.TokenType;

/**
 * Parses the LOGO statements grammar Grammar: zero or more statement
 */
public class LogoStatements extends LogoGrammar {
	private ArrayList<LogoStatement> statements;

	public LogoStatements(TokenIterator it, TokenType end, boolean inclusive) throws LogoParseException {
		statements = new ArrayList<LogoStatement>();
		parseTokens(it, end);

		// If the end of a LogoStatements section should also consume the end
		// token, consume it.
		if (inclusive) {
			it.next();
		}
	}

	private void parseTokens(TokenIterator it, TokenType endToken) throws LogoParseException {
		while (it.hasNext()) {
			TokenType type = it.peek().getType();

			if (type == endToken) {
				return;
			}

			statements.add(LogoStatementParser.parseStatement(it));
		}
	}

	@Override
	public void resolveIdentifiers(LogoScope scope) throws LogoParseException {
		for (LogoStatement statement : statements) {
			statement.resolveIdentifiers(scope);
		}
	}

	/**
	 * Example output: 5 forward 11 LDRAGON ... etc
	 */
	@Override
	public void generatePostScriptCode(PrintWriter stream) {
		for (LogoStatement statement : statements) {
			statement.generatePostScriptCode(stream);
		}
	}

}
